package array

func generateMatrix(n int) [][]int {
	res := make([][]int, n)
	for i := 0; i < n; i++ {
		res[i] = make([]int, n)
	}

	top, left := 0, 0
	bottom, right := n-1, n-1

	num := 1

	for top <= bottom && left <= right {
		// 从[top][left]向右至[top][right]
		for i := left; i <= right; i++ {
			res[top][i] = num
			num++
		}

		// 从[top+1][right]向下到[bottom][right]
		for i := top + 1; i <= bottom; i++ {
			res[i][right] = num
			num++
		}

		// 从[bottom][right-1]向左至[bottom][left]
		for i := right - 1; i >= left; i-- {
			res[bottom][i] = num
			num++
		}

		// 从[bottom-1][left]向上至[top+1][left]
		for i := bottom - 1; i > top; i-- {
			res[i][left] = num
			num++
		}

		left++
		top++
		right--
		bottom--
	}

	return res

}
